import { 
  generateCaptcha, 
  verifyCaptcha, 
  verifyCredentials, 
  createSession, 
  destroySession,
  verifySession,
  getSessionUser,
  changePassword
} from '../utils/auth.js';

// 获取验证码
export const getCaptcha = (req, res) => {
  try {
    const captcha = generateCaptcha();
    res.json(captcha);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 登录
export const login = (req, res) => {
  try {
    const { username, password, captchaId, captchaAnswer } = req.body;
    
    if (!username || !password || !captchaId || !captchaAnswer) {
      return res.status(400).json({ error: '缺少必要字段' });
    }
    
    // 验证验证码
    if (!verifyCaptcha(captchaId, captchaAnswer)) {
      return res.status(400).json({ error: '验证码错误或已过期' });
    }
    
    // 验证用户凭证
    if (!verifyCredentials(username, password)) {
      return res.status(401).json({ error: '用户名或密码错误' });
    }
    
    // 创建会话
    const token = createSession(username);
    res.json({ 
      token,
      username,
      message: '登录成功' 
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 登出
export const logout = (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    if (token) {
      destroySession(token);
    }
    res.json({ message: '登出成功' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 验证会话
export const verify = (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token || !verifySession(token)) {
      return res.status(401).json({ valid: false });
    }
    
    res.json({ valid: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 修改密码（需要认证）
export const changePasswordRoute = (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token || !verifySession(token)) {
      return res.status(401).json({ error: '未授权，请先登录' });
    }
    
    const { oldPassword, newPassword } = req.body;
    
    if (!oldPassword || !newPassword) {
      return res.status(400).json({ error: '缺少必要字段' });
    }
    
    // 获取当前用户
    const username = getSessionUser(token);
    if (!username) {
      return res.status(401).json({ error: '会话无效' });
    }
    
    // 修改密码
    const result = changePassword(username, oldPassword, newPassword);
    
    if (!result.success) {
      return res.status(400).json({ error: result.error });
    }
    
    res.json({ message: result.message });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

